<template>
  <div>
    <myDivider :name="type == 'detail' ? '设备详情' : '新增设备'"></myDivider>
    <el-page-header @back="$router.back(-1)">
    </el-page-header>
    <el-form style="width: 600px;margin-top: 50px;" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px"
      class="demo-ruleForm">
      <el-form-item v-if="type == 'detail'" label="设备编号" prop="number">
        <el-input style="width: 200px;" v-model="ruleForm.number" disabled></el-input>
      </el-form-item>
      <div style="display: flex;">

        <el-form-item label="设备类别" prop="categoryNumber">
          <el-select v-model="ruleForm.categoryNumber" filterable placeholder="选择设备类别" style="width: 200px;" clearable
            @change="getCategoryNameData">
            <el-option v-for="item in categoryData" :key="item.number" :label="item.name" :value="item.number">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="设备名称" prop="nameNumber">
          <el-select v-model="ruleForm.nameNumber" filterable placeholder="选择设备名称" style="width: 200px;" clearable>
            <el-option v-for="item in categoryNameData" :key="item.number" :label="item.name" :value="item.number">
            </el-option>
          </el-select>
        </el-form-item>
      </div>

      <div style="display: flex;">
        <el-form-item label="规格型号" prop="model">
          <el-input maxlength="20" style="width: 200px;" v-model="ruleForm.model" placeholder="请填写规格型号"></el-input>
        </el-form-item>
      </div>

      <div style="display: flex;">
        <el-form-item label="数量" prop="count">
          <el-input oninput="value=value.replace(/[^\d]/g,'');if(value.length>4){value=value.slice(0,4)}" type="number"
            v-model="ruleForm.count" maxlength="10" placeholder="请填写设备数量"></el-input>


        </el-form-item>
        <el-form-item label="使用区域" prop="area">
          <el-input style="width: 200px;" maxlength="20" v-model="ruleForm.area" placeholder="请填写使用区域"></el-input>
        </el-form-item>
      </div>

      <div style="display: flex;">
        <el-form-item label="资产原值" prop="cost">
          <!-- <el-input style="width: 180px;" v-model="ruleForm.cost" placeholder="保留小数点后两位"></el-input> 元 -->
          <el-input style="width: 180px;" type="number" v-model="ruleForm.cost"
            oninput="if(value.length>10){value=value.slice(0,10)}" placeholder="保留小数点后两位"></el-input>&nbsp;元

        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select v-model="ruleForm.state" placeholder="请选择使用状态" style="width: 200px;">
            <el-option v-for="item in stateOptionsData" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </div>






      <el-form-item label="备注" prop="description">
        <el-input style="width: 500px;" v-model="ruleForm.description" type="textarea" :rows="5" maxlength="200"
          show-word-limit placeholder="最多输入200字..."></el-input>
      </el-form-item>

      <el-form-item label="图片" prop="">
        <myuploadLimit3 v-if="ifupdate" ref="byimg" @getImgList="getImgList"
          uploadUrl="/business/facilities/uploadImg"
          deleteUrl="/business/facilities/deleteImg" :FileList="FileList"></myuploadLimit3>
        <!-- <div class="imglist" v-else>
          <el-image class="el" style="width: 100px; height: 100px" v-for="item, i in ruleForm.imgs" :key="i" :src="item"
            :preview-src-list="ruleForm.imgs">
          </el-image>
        </div> -->
      </el-form-item>

      <el-form-item label="经办人" prop="" required>
        <el-input disabled style="width: 200px;" v-model="ruleForm.userName" placeholder="自动匹配"></el-input>
      </el-form-item>


      <el-form-item class="btn" v-if="type == 'add'">
        <el-button style="width: 100px;" type="primary" @click="submitForm('ruleForm')">新增</el-button>
        <el-button style="width: 100px;" type="info" @click="resetForm('ruleForm')">取消</el-button>
      </el-form-item>

      <el-form-item class="btn" v-if="type == 'detail'">
        <el-button style="width: 100px;" type="info" @click="resetForm('ruleForm')">取消</el-button>
        <el-button style="width: 100px;" type="primary" @click="submitFormForUpdate('ruleForm')">修改</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>

<script>
window._AMapSecurityConfig = {
  securityJsCode: "74a9bc741a93c4984284167952f22f4a",//安全密钥
};
import 'default-passive-events'
import myuploadByCHGLFile from '../../components/upload/myuploadByCHGLFile';
import myuploadLimit3 from '../../components/myuploadLimit3'
export default {
  components: {
    myuploadByCHGLFile,
    myuploadLimit3
  },
  data() {
    return {
      categoryData: {},
      categoryNameData: {},
      stateOptionsData: [{ "id": 1, "name": "正常使用" }, { "id": 2, "name": "暂停使用" }],

      type: '',//新增还是详情
      keyAddress: '',
      ruleForm: {},
      rules: {
        categoryNumber: [
          { required: true, message: '请选择设备类别', trigger: 'change' }
        ],
        nameNumber: [
          { required: true, message: '请选择设备名称', trigger: 'change' }
        ],
        state: [
          { required: true, message: '请选择设备状态', trigger: 'change' }
        ],
        userName: [
          { required: true, message: '请填写经办人', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请填写详细位置', trigger: 'blur' }
        ],
        cost: [
          { required: true, trigger: 'change', message: '请输入金额' },
          { pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '请输入正确的格式,可保留两位小数' }
        ],
      },
      map: null,//地图
      marker: null,//点标点
      geocoder: null,//编码
      MyannexPathArr: [],
      FileList: [],
      ifupdate: false,
    };
  },
  async activated() {
    this.type = this.$route.query.type //新增？详情？
    this.getCategoryData();
    if (this.type == 'add') {
      this.ifupdate = true
      let res = await this.$api.metting.getLoginUser() //经办人回显
      this.$set(this.ruleForm, 'userName', res.data.name)

    } else {
      this.detailData();
    }
    this.$nextTick(() => { //清除验证
      this.$refs['ruleForm'].clearValidate()
    })
  },
  deactivated() {
    // 销毁了，挨个清空表单值
    this.$set(this.ruleForm, 'categoryNumber', '')
    this.$set(this.ruleForm, 'address', '')
    this.$set(this.ruleForm, 'area', '')
    this.$set(this.ruleForm, 'cost', '')
    this.$set(this.ruleForm, 'count', '')
    this.$set(this.ruleForm, 'model', '')
    this.$set(this.ruleForm, 'imgs', [])
    this.$set(this.ruleForm, 'nameNumber', '')
    this.$set(this.ruleForm, 'state', '')
    this.$set(this.ruleForm, 'description', '')
    if (this.type == 'add') {
      // 清空图片
      this.$refs.byimg.clear()
    }

  },
  methods: {
    async getCategoryData() {
      let res = await this.$api.facility.getCategoryList()
      this.categoryData = res.data
    },
    async getCategoryNameData() {
      this.$set(this.ruleForm, 'nameNumber', '')
      let res = await this.$api.facility.getCategoryNameList(this.ruleForm.categoryNumber)
      this.categoryNameData = res.data

      this.$nextTick(() => {
        this.$refs.ruleForm.clearValidate()
      })
    },



    getFileList(files) { //附件列表
      this.$set(this.ruleForm, 'annexPathArr', files)
    },
    getImgList(imgs) { //图片列表
      console.log(imgs)
      this.$set(this.ruleForm, 'imgs', imgs)
      console.log(this.ruleForm)
    },
    // 输入关键字定位
    addressChange() {
      this.geocoder.getLocation(this.keyAddress, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          // result中对应详细地理坐标信息
          console.log(result.geocodes[0].location);
          let lng = result.geocodes[0].location.lng
          let lat = result.geocodes[0].location.lat
          this.map.setCenter([lng, lat], true)
          this.map.setZoom(14)
          this.marker = new AMap.Marker({ //创建点标点
            position: [lng, lat],
          });
          this.map.add(this.marker);
        }
      })
    },
    async detailData() { //数据回显
      this.ifupdate = false
      let id = this.$route.query.id
      let res = await this.$api.facility.getFacilityDetail(id)
      this.$set(this.ruleForm, 'categoryNumber', res.data.categoryNumber)
      this.getCategoryNameData();
      this.ruleForm = res.data
      if (this.ruleForm.imgs) {
        this.FileList = this.ruleForm.imgs
      } else {
        this.FileList = []
      }

      console.log(this.ruleForm, 'bbbbbb')


      this.ifupdate = true
    },

    submitForm(formName) {
      if (this.type == 'detail') {
        return
      }
      this.$refs[formName].validate(async (valid) => {
        if (valid) {

          if (this.ruleForm.imgs == undefined || this.ruleForm.imgs.length < 1) { //如果图片为空或者图片数量为0
            this.ruleForm.imgs = []
          }
          let res = await this.$api.facility.insertFacility(this.ruleForm)
          if (res.code == 200) {
            this.$message({
              message: '记录新增成功',
              type: 'success'
            });
            this.$router.back(-1)
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    submitFormForUpdate(formName) {
      if (this.type == 'add') {
        return
      }
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (this.ruleForm.imgs == undefined || this.ruleForm.imgs.length < 1) { //如果图片为空或者图片数量为0
            this.ruleForm.imgs = []
          }
          this.$confirm('是否保存修改?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            let res = await this.$api.facility.updateFacility(this.ruleForm)
            if (res.code == 200) {
              this.$message({
                message: '记录修改成功',
                type: 'success'
              });
              this.$router.back(-1)
            }
          }).catch(() => {

          });

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$router.back(-1)
    }
  }
}
</script>
<style lang="less" scoped>
.annexBox {
  width: 500px;

  .annexList {
    width: 100%;
    box-sizing: border-box;
    border-right: 3px solid rgb(23, 197, 255);

    .el {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;

      span {
        &:nth-child(1) {
          width: 300px;
          display: block;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        &:nth-child(2) {
          color: rgb(23, 197, 255);
          cursor: pointer;
          margin-right: 10px;
        }
      }
    }
  }

  .annexNone {
    color: #aaa;
  }
}

.btn {
  position: fixed;
  bottom: 10px;
  right: 40px;
}

.imglist {
  .el {
    border-radius: 5px;
    overflow: hidden;
    margin-right: 10px;
  }
}

.mapStyle {
  height: 400px;
  width: 1100px;
  margin-left: 100px;
  position: relative;
  margin-bottom: 100px;

  #container {
    padding: 0px;
    margin: 0px;
    width: 100%;
    height: 100%;

  }

  .keyAddressStyle {
    position: absolute;
    right: 15px;
    top: 15px;
    width: 250px;
    height: 30px;
  }
}
</style>